<template>
	<view :class="['ui-upload-image', `ui-upload-image__${uploadType}`]">
		<!-- 支持全部文件类型 -->
		<template v-if="type === 'all'">
			<lsj-upload v-if="!isPreview && !showDefaultList.length" ref="lsjRef" :childId="childId" height="200rpx" 
			:formats="formats" :size="fileSize" :count="max" :multiple="max > 1" :instantly="true" :option="option" 
			@change="change" @uploadEnd="uploadFileEnd">
				<fui-icon class="ui-upload-btn" name="plus" size="68" color="#999"></fui-icon>
			</lsj-upload>
			<view class="ui-upload-list" v-else>
				<view class="ui-upload-item" v-for="(item, index) in showDefaultList" :key="index">
					<fui-icon v-if="!isPreview" name="order" size="36" color="var(--fui-color-primary)"></fui-icon>
					<text>{{ getFileName(item) }}</text>
					<fui-icon v-if="!isPreview" class="ui-upload-delete" name="minussign-fill" size="36" color="#FF2B2B" @click="deleteFile(index)"></fui-icon>
					<fui-icon v-else class="ui-upload-download" name="top" size="36" color="var(--fui-color-primary)" @click="downloadFile(item)"></fui-icon>
				</view>
			</view>
		</template>

		<!-- 指定证件/图片 -->
		<fui-upload v-else immediate :url="url" :header="header"
			:class="[`ui-upload-item__${type}`, {'ui-upload-item__one': max <= 1}]" :style="uploadStyle" call-upload
			ref="uploaderRef" :max="max" :fileList="showDefaultList" @success="success" @error="error"
			@complete="complete">
			<view v-if="uploadType !== 'normal'"></view>
			<fui-icon v-else name="plus" size="68" color="#999"></fui-icon>
		</fui-upload>
		<fui-text v-if="type === 'front'" class="ui-upload-image__text">身份证正面</fui-text>
		<fui-text v-if="type === 'back'" class="ui-upload-image__text">身份证反面</fui-text>
	</view>
</template>

<script setup>
	import { ref, computed, watch, inject } from 'vue'
	import { useStore } from 'vuex'
	import config from '@/config'
	import { getAccessToken } from '@/utils/auth'
	import { getFileName, downloadFile } from '@/utils/tools'

	const modal = inject('$modal')
	const store = useStore()

	const props = defineProps({
		isPreview: {
			type: Boolean
		},
		type: {
			type: String, // 'business' || 'front' || 'back' || 'avatar' || 'all'
			default: 'image'
		},
		size: {
			type: String, // 'small' || 'default'
			default: 'default'
		},
		max: {
			type: Number || String,
			default: 1
		},
		defaultList: {
			type: Array,
			default: []
		},

		// 使用多文件类型组件
		childId: {
			type: String,
			default: 'lsjUpload'
		},
		fileSize: {
			type: Number,
			default: 30
		},
		formats: String
	})

	const showDefaultList = ref([])
	watch(props, (val) => {
		showDefaultList.value = props.defaultList
	}, {
		immediate: true,
    deep: true
	})

	const url = config.baseUrl + config.baseApi + '/infra/file/upload'
	const header = computed(() => {
		return {
			Authorization: 'Bearer ' + getAccessToken(),
			'tenant-id': store.getters.currentTenantId
		}
	})
	const option = computed(() => {
		return {
			url,
			header: header.value,
			name: 'file'
		}
	})
	const uploadType = computed(() => {
		return (props.type === 'image' || props.type === 'avatar' || props.type === 'all') ? 'normal' : 'certificate'
	})
	const uploadStyle = computed(() => {
		let style = {}
		if (uploadType.value !== 'normal') {
			style = {
				height: props.size === 'small' ? '174rpx' : '360rpx',
				padding: props.size === 'small' ? '14rpx 52rpx' : '40rpx 108rpx'
			}
		}
		return style
	})

	const emits = defineEmits(['uploaded'])

	// fui组件
	const uploaderRef = ref(null)
	const fileList = ref([])
	const success = (e) => {
		const res = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}")
		if (res.code === 0 && res.data) {
			uploaderRef.value.result(res.data, e.index)
		} else {
			if (res.msg) {
				modal.msg(res.msg)
			} else {
				modal.msg('上传失败！')
			}
		}
	}
	const error = (e) => {
		modal.msg('上传失败！')
	}
	const complete = (e) => {
    fileList.value = e.urls
    if (e.action === 'delete') {
			emits('uploaded', fileList.value)
		}
		if (e.action === 'upload' && e.status === 'success') {
			emits('uploaded', fileList.value)
		}
	}

	// lsj-upload组件
	const lsjRef = ref(null)
	let selectList = new Map()
	const change = (list) => {
		if (!list.type) {
			modal.loading()
			selectList = list
		}
	}
	const uploadFileEnd = (item) => {
		selectList.set(item.name, item)

		if (item.responseText) {
			const res = JSON.parse(item.responseText)
			selectList.get(item.name).responseText = res
			fileList.value.push(res.data)
		}

		const isAll = [...selectList.values()].find(subitem => subitem.type !== 'success')
		if (!isAll) {
			modal.closeLoading()
      emits('uploaded', fileList.value)
			console.log(fileList.value, '已全部上传完毕')
		} else {
			console.log(isAll.name + '待上传')
		}
	}
	const deleteFile = (index) => {
		fileList.value.splice(index, 1)
		emits('uploaded', fileList.value)
	}
</script>

<style lang="scss" scoped>
	.ui-upload-image {
		&.ui-upload-image__certificate {
			position: relative;
			width: 100%;

			&:nth-child(2) {
				margin-left: 22rpx;
			}

			::v-deep .fui-upload__wrap {
				width: 100%;
				height: 100%;
				overflow: hidden;
				background-color: #fff;
				border: 2rpx dashed #d4d4d4;
				border-radius: 20rpx;
				box-sizing: border-box;

				&.ui-upload-item__business .fui-upload__item {
					background-image: url("/static/images/upload-business.png") !important;
				}

				&.ui-upload-item__front .fui-upload__item {
					background-image: url("/static/images/upload-front.png") !important;
				}

				&.ui-upload-item__back .fui-upload__item {
					background-image: url("/static/images/upload-back.png") !important;
				}

				&.ui-upload-item__front,
				&.ui-upload-item__back {
					margin-bottom: 56rpx;
				}

				.fui-upload__item {
					flex: 1;
					width: 100% !important;
					height: 100% !important;
					background-size: 100% 100% !important;
					background-repeat: no-repeat !important;
					background-position: center center !important;
					background-color: #fff !important;
					margin: 0 !important;
					padding: 12rpx;

					.fui-upload__img {
						width: 100% !important;
						height: 100% !important;
						background-color: #fff;
					}
				}
			}

			.ui-upload-image__text {
				position: absolute;
				left: 50%;
				bottom: 8rpx;
				transform: translateX(-50%);
				font-size: 20rpx;
				color: #999;
			}
		}

		&.ui-upload-image__normal {
			::v-deep .fui-upload__wrap {
				&.ui-upload-item__one {
					.fui-upload__item {
						margin: 0;
					}
				}

				&.ui-upload-item__avatar {
					.fui-upload__item {
						flex: 0 0 132rpx;
						width: 132rpx !important;
						height: 132rpx !important;

						.fui-upload__img {
							border-radius: 50% !important;
						}

						.fui-upload__del {
							top: 0;
							right: 0;
						}
					}
				}

				.fui-upload__item {
					flex: 0 0 calc(25% - 15rpx);
					width: calc(25% - 15rpx) !important;
					height: 132rpx !important;
					border-radius: 8rpx !important;
					margin-right: 20rpx;
					margin-bottom: 20rpx;

					&:nth-child(4n) {
						margin-right: 0;
					}

					.fui-upload__img {
						width: 100% !important;
						height: 100% !important;
						border-radius: 8rpx !important;
						background-color: #fff;
					}
				}
			}
		}

		::v-deep .hFile {
			display: flex;
			align-items: center;
			width: 100%;
			height: 200rpx;
			background-color: #fff;
			border: 2rpx dashed #d4d4d4;
			border-radius: 20rpx;
			box-sizing: border-box;
			.ui-upload-btn {
				display: block;
				margin: 40rpx auto;
			}
		}
		.ui-upload-list {
			.ui-upload-item {
				position: relative;
				padding-right: 48rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				&:not(:last-child) {
					border-bottom: 2rpx dashed #d4d4d4;
					margin-bottom: 16rpx;
					padding-bottom: 16rpx;
				}
				.fui-icon {
					margin-right: 10rpx;
				}
				.ui-upload-delete {
					position: absolute;
					top: 0;
					right: 0;
					margin-top: 4rpx;
				}
				.ui-upload-download {
					position: absolute;
					top: -4rpx;
					right: 0;
					transform: rotate(180deg);
				}
			}
		}
	}
</style>